package org.jeecg.modules.commodity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.commodity.entity.CommodityType;
import org.jeecg.modules.commodity.service.CommodityTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: zhuzhuhong
 * @Date: 2019/11/12 14:57
 * @Description: 商品类型控制层
 */
@Log4j2
@RestController
@RequestMapping(value = "/commodity/commodityType")
public class CommodityTypeController {
    @Autowired
    private CommodityTypeService commodityTypeService;

    @GetMapping(value = "/list")
    public Result<IPage<CommodityType>> findCommodityType(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request){
        Result<IPage<CommodityType>> pageResult = new Result<>();
        try {
            //处理参数,将商品类型名称封装到QueryWrapper对象中
            String typeName = request.getParameter("typeName");
            QueryWrapper<CommodityType> queryWrapper = new QueryWrapper<CommodityType>()
                    .like(StringUtils.isNotBlank(typeName) ? true : false,
                    "type_name", typeName);
            IPage<CommodityType> page = new Page<>();
            //执行查询操作
            commodityTypeService.page(page, queryWrapper);
            pageResult.setResult(page);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            pageResult.error500("后台异常");
        }
        return pageResult;
    }

    @PostMapping(value = "/add")
    public Result<Object> addCommodityType(@RequestBody CommodityType commodityType) {
        Result<Object> result = new Result<>();
        try {
            //执行新增操作
            boolean saveResult = commodityTypeService.save(commodityType);
            if (!saveResult) {
                result = Result.error("新增失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("后台异常");
        }
        return result;
    }

}
